
package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.vo.InvoiceVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceConroller extends BaseController{
    @Reference
    private InvoiceService invoiceService;

    @Reference
    private ShippingOrderService shippingOrderService;

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private PackingService packingService;

    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(name="分页查询发票信息",path = "/list")
    public String list(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "5")int size){
        //1.通过service分页查询数据
        PageInfo info = invoiceService.findAll(page, size, null);
        //2.存入request域中
        request.setAttribute("page",info);
        //3.转发
        return "/cargo/invoice/invoice-list";
    }

    @RequestMapping(name="跳转至添加发票",path = "/toAdd")
    public String toAdd(){
        //查询未打印发票的委托单信息
        ShippigOrderExample example = new ShippigOrderExample();
        ShippigOrderExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(0);
        List<ShippigOrder> list = shippingOrderService.findAll(example);
        request.setAttribute("shippingList",list);
        return "/cargo/invoice/invoice-add";
    }

    @RequestMapping(name="删除发票",path = "/delete")
    public @ResponseBody boolean delete(String id){
        //1.查询发票状态
        Invoice invoice = invoiceService.findById(id);
        //2.判断发票状态是否为草稿状态 0
        if (invoice.getState() == 0) {
            //3.为草稿，调用service层 完成发票删除
            invoiceService.delete(id);
            return true;
        }else{
            //4.不为草稿返回false
            return false;
        }
    }

    @RequestMapping(name="新增发票信息",path="/edit")
    public String edit(Invoice invoice){
        invoiceService.save(invoice);
        return "redirect:/cargo/invoice/list.do";

    }


    //打印报表
    @RequestMapping("/printPdf")
    public void printPdf(String id) throws IOException {
        Invoice invoice = invoiceService.findById(id);
        Map map = new HashMap();
        map.put("seller",invoice.getSeller());
        map.put("buyer",invoice.getBuyer());
        map.put("pobox",invoice.getPobox());
        map.put("invoiceNo",invoice.getId());
        map.put("date",invoice.getCreateDate());
        map.put("scNo",invoice.getScNo());
        map.put("blNo",invoice.getBlNo());

        ShippigOrder shipp = shippingOrderService.findById(id);
        map.put("lcNo", shipp.getLcNo());
        map.put("orderType", shipp.getOrderType());
        map.put("loading", shipp.getPortOfLoading());
        map.put("discharge", shipp.getPortOfDischarge());
        String ids[] = {id};

        List<InvoiceVo> list = new ArrayList<>();
        Packing packing = packingService.findById(id);
        System.out.println(packing);

        String[] exportIds = packing.getExportIds().split(",");
        System.out.println(Arrays.toString(exportIds));
        for (String exportId : exportIds) {
            Export byId = exportService.findById(exportId);
            System.out.println(byId);
            ExportProductExample example = new ExportProductExample();
            ExportProductExample.Criteria criteria = example.createCriteria();
            criteria.andExportIdEqualTo(exportId);
            List<ExportProduct> all = exportProductService.findAll(example);
            System.out.println(all.size());
            for (ExportProduct exportProduct : all) {
                InvoiceVo invoiceVo = new InvoiceVo();
                invoiceVo.setMarks(byId.getMarks());
                invoiceVo.setDescriptions(packing.getDescription());
                invoiceVo.setDescriptions(packing.getDescription());
                invoiceVo.setQuantity(exportProduct.getCnumber());
                invoiceVo.setUnit(exportProduct.getPrice());
                invoiceVo.setAmount(exportProduct.getCnumber()*exportProduct.getPrice());
                invoiceVo.setPsc(exportProduct.getPackingUnit());
                list.add(invoiceVo);
            }

        }
        for (InvoiceVo invoiceVo : list) {
            System.out.println(invoiceVo);
        }
        System.out.println(1);
        //1.准备数据
        //2.设置下载信息
        response.setContentType("application/vnd.ms-excel"); //下载excel
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("发票单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //3.加载excel模板
        String path = session.getServletContext().getRealPath("/")+"/make/invoice.xlsx";
        //4.创建EasyExcel的excelWtire对象( 用于数据填充)
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .head(ContractProductVo.class) //设置表头
                .withTemplate(path) //加载模板
                .build();
        //获取sheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        //5.调用方法完成填充map数据
        excelWriter.fill(map, sheet);
        //6.调用方法完成填充list数据
        excelWriter.fill(list, sheet);
        //7.属性资源，完成下载
        excelWriter.finish(); //下载excel文件，释放内存资源
    }



}